<!--地图层 -->
<div id="container" style="display: none;position: fixed;top: 0px;left:0px;right:0px;bottom:60px;z-index: 22;background: #fff;">
	<div id="googleMap" style="width:100%;height:100%;"></div>
	<div class="row" style="margin:5px;" >
		<div class="input-group">
			<input id="address_input" type="text" class="form-control" placeholder="输入地址或者地图选择地址" style="font-weight: bold;color:#00f;" />
			<span id="address_search" class="input-group-text bi-search btn-secondary"></span>
			<span id="address_get" class="input-group-text bi-check-lg btn-primary" style="display: block;"></span>

		</div>
	</div>
</div>


<style>
	.custom-map-control-button{margin:20px 2px;border-radius: 10px;border-width: 1px;box-shadow: 1px 1px 3px #f60;padding: 5px;}
</style>
<script>
	// google.maps.MapTypeId.HYBRID      ：显示卫星图像的主要街道透明层
	// google.maps.MapTypeId.ROADMAP      ：显示普通的街道地图
	// google.maps.MapTypeId.SATELLITE    ：显示卫星图像


	//附近地点数组
	var nearby=[];
	
	//路线数据
	var route_obj={
		address_start:'',
		address_end:'',
		distance: 0,
		duration:''
	};
	var current_pos='';

	var base_distance=0;
	var distance=0;
	var base_price=0;
	var price_per_km=0;


	//加载地图资源
	function loadScript(){
	  var script = document.createElement("script");
	  script.type = "text/javascript";
	  script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyB6GHAYtKuxzrTKcbwi6VWg65TmOuI5608&libraries=places&sensor=true&callback=initialize";
	  document.body.appendChild(script);
	}
	var outTextQuery=null;
	var outCalcRoute=null;
	var a_find=0;

	//地图初始化函数，定义地图中心，属性，类型等
	function initialize(){
		var infoWindow;
		var center=new google.maps.LatLng(11.569593, 104.920915);

		
		//地图属性
		var mapProp = {
			center: center,
			zoom:15,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			panControl:false,
			zoomControl:true,
			mapTypeControl:false,
			scaleControl:true,
			streetViewControl:false,
			overviewMapControl:true,
			rotateControl:false
		};

		//地图建立
		var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);

		//地理定位到当前位置,需要准备一些东西//////////////////////////////////////////////////
		infoWindow = new google.maps.InfoWindow({content:'Location found!'});
		const locationButton = document.createElement("button");
		const nearbyButton = document.createElement("button");
		const closeMapButton = document.createElement("button");
		// const calcRouteButton = document.createElement("button");

		//addtional buttons 
		locationButton.textContent = "当前位置";
		nearbyButton.textContent = "附近地址";
		// calcRouteButton.textContent = "路线规划";
		closeMapButton.textContent = "退出(Exit)";

		locationButton.classList.add("custom-map-control-button");
		nearbyButton.classList.add("custom-map-control-button");
		// calcRouteButton.classList.add("custom-map-control-button");
		closeMapButton.classList.add("custom-map-control-button");

		map.controls[google.maps.ControlPosition.BOTTOM].push(locationButton);
		map.controls[google.maps.ControlPosition.BOTTOM].push(nearbyButton);
		// map.controls[google.maps.ControlPosition.BOTTOM].push(calcRouteButton);
		map.controls[google.maps.ControlPosition.BOTTOM].push(closeMapButton);


		locationButton.addEventListener("click",whereIsHere);
		//找出当前的定位
		function whereIsHere(){
			// Try HTML5 geolocation.
			if (navigator.geolocation) {
				navigator.geolocation.getCurrentPosition(
				  success=>{

				  	//console.log(success);
					const pos = {
						lat: success.coords.latitude,
						lng: success.coords.longitude,
					};

					//显示位置信息
					setMarker(pos,'˙ω˙');
					map.panTo(pos);
					//setTimeout(function(){setInfo(pos,"let's go!!!!!!!!!!!!!",map);},2000)
					center =  pos;
					current_pos = pos;
					find_city(pos);

				}
				,function(error){alert(error.message);}//定位出错的信息显示
				,{
				 //可增加的4个配置参数
				  enableHighAccuracy:true,//高精度
				  timeout:5000,//超时时间,以ms为单位
				  maximumAge:24*60*60*1000,//位置缓存时间,以ms为单位
				}
				);
			} else {
				alert("Browser doesn't support Geolocation");

			}
		}

		////定位当前位置////////////////////////////////////////////////// 		

		//清除markers
		function cleanMarkers(){
			console.log('There are '+markers.length+' markers,now clean markers...');

			for(i in markers){
				markers[i].setMap(null);
				markers[i]=null;
			}
			markers.length=0;
			console.log('There are '+markers.length+" markers");


			for(i in circles){
				circles[i].setMap(null);
			}
			circles.length=0;

		}

		//退出地图
		closeMapButton.addEventListener('click',function(){
			document.getElementById('container').style.display='none';
		});



		//文本搜索地址
		function textQuery(place){
		  if(!place.trim()) {alert('请输入你要搜索的地址关键字!');return;}
		  var request = {
		    query: place,
		    fields: ['name', 'geometry'],
		  };

		  var service = new google.maps.places.PlacesService(map);

		  service.findPlaceFromQuery(request, function(results, status) {
		    if (status === google.maps.places.PlacesServiceStatus.OK) {
		      //for (var i = 0; i < results.length; i++) {
		      setMarker(results[0].geometry.location,'°ο°');
		      //}
		      map.panTo(results[0].geometry.location);
		      center = results[0].geometry.location;
		    }
		  });
		}

		//draw with a circel
		var circles=[];
		function drawCircle(pos,radius){
			for(i in circles){
				circles[i].setMap(null);
			}
			circles.length=0;

		    var circle = new google.maps.Circle({
		      strokeColor: "#FF6600",
		      strokeOpacity: 0.5,
		      strokeWeight: 1,
		      fillColor: "#0000ff",
		      fillOpacity: 0.1,
		      map,
		      center: center,
		      radius:radius 
		    });
		    circles.push(circle);
		}


		/*--------------------------------------------------------------
		地图监听事件,在点击的位置创建标记
		如果有placeId,取得他的资料
		*/
		map.addListener("click",mapClick);
		function mapClick(e){
			console.log({'Event for map click':e});
			map.panTo(e.latLng);
			center = e.latLng;

			//get infomation of the marker is clicked.
			if(e.placeId){
				var service = new google.maps.places.PlacesService(map);	
				var request = {
					placeId:e.placeId
				};				
				service.getDetails(request,function(result,status){
					if(status=='OK'){
						console.log({status:status,result:result});
						//setMarker(e.latLng,'O',e.placeId);
						document.getElementById('address_input').value="["+result.name+"]"+result.formatted_address;
						document.getElementById('pos'+a_find).value=JSON.stringify(result.geometry.location);
					}else{
						alert('From google:['+status+']');
					}
					

				});
			}else{
				//set a new marker when no any placeId found.
				cleanMarkers();
				setMarker(e.latLng,'˙ω˙');
			}
		}
		//------------------------------------------------------------------

		
		//做标记，标记内容，信息窗
		var markers=[]; //标记数组
		function setMarker(pos,txt='',placeId=''){
			//console.log({'set marker at pos':pos,'placeId':placeId});
			var marker=new google.maps.Marker({
				position:pos,
				map,
				//icon:svgMarker
				//animation:google.maps.Animation.BOUNCE //一动一动的图标
			});

			if(txt) {marker.setLabel(txt+'');}
			markers.push(marker);

			
			//做自己的标记
			if(placeId){
				google.maps.event.addListener(marker, 'click', function() {
					console.log('Marker on placeId:'+placeId);

					//查出图标的详细资料
					var service = new google.maps.places.PlacesService(map);	
					var request = {
						placeId:placeId
					};

					service.getDetails(request,function(result,status){
						if(status=='OK'){
							console.log({'place detail':{status:status,result:result}});
							var infoTxt = "<div style='font-weight:bold;color:blue;'>"+result.name+"</div><div>"+result.formatted_address+"</div>";
								infoTxt+="<div style='border-top:1px solid #ccc;'><a style='color:blue;' href='"+result.url+"' target='_blank'>Google for this place</a></div>";
							setInfo(pos,infoTxt,map);
							
							document.getElementById('address_input').value="["+result.name+"]"+result.formatted_address;
							document.getElementById('pos'+a_find).value=JSON.stringify(result.geometry.location);

						}else{
							alert('From google:['+status+']');
						}

					});


				});
			}

			//marker.setMap(map); 
		}


		//附近搜索
		nearbyButton.addEventListener("click",nsearch);
		function nsearch(){
			var request = {
				location: center,
				radius: '500',
				//type: ['school','hotel','casino','market']
			};			
			var service = new google.maps.places.PlacesService(map);
			service.nearbySearch(request,function(results, status) {
			  if (status == google.maps.places.PlacesServiceStatus.OK) {
			  	cleanMarkers();

			    for (var i = 0; i < results.length; i++) {
			      //console.log(results[i].geometry.location);
				  setMarker(results[i].geometry.location,i+1,results[i].place_id);
			    }
			    
			    //drawCircle(center,500);
			  }else{

			  	alert('No any location found!');
			  }
			});
		}


		//auto location current city
		function find_city(pos){
			var request = {
				location: center,
				radius: '1000',
			};

			var service = new google.maps.places.PlacesService(map);
			service.nearbySearch(request,function(results, status) {
			  if (status == google.maps.places.PlacesServiceStatus.OK) {
			  	
			    var city=results[0].name;
			    document.getElementById('init_city').innerText = city?city:'';
			    //drawCircle(center,500);
			  }else{

			  	alert('Sorry,you are in an unknow place!');
			  }
			});
		}


		/*路线规划
		directionsService的返回值status如下:
		1.OK 表示响应中包含有效的 DirectionsResult。
		2.NOT_FOUND 表示请求的出发地、目的地或航点中指定的位置中至少有一个无法接受地理编码。
		3.ZERO_RESULTS 表示在出发地和目的地之间找不到路线。
		4.MAX_WAYPOINTS_EXCEEDED 表示 DirectionsRequest 中提供的 DirectionsWaypoint 字段过多。请参阅下文的航点限制部分。
		5.MAX_ROUTE_LENGTH_EXCEEDED 表示所请求的路线过长，无法进行处理。当系统返回更复杂的路线时，就会发生此错误。不妨尝试减少航点、转弯或指示的数量。
		6.INVALID_REQUEST 表示提供的 DirectionsRequest 无效。导致出现此错误代码的最常见原因包括：请求中缺少出发地或目的地；或者公交请求中包含航点。
		7.OVER_QUERY_LIMIT 表示网页在允许的时间段内发送的请求过多。
		8.REQUEST_DENIED 表示不允许网页使用路线服务。
		9.UNKNOWN_ERROR 表示因服务器错误而无法处理路线请求。如果您重试，请求可能会成功。
		*/

		calcRouteButton.addEventListener('click',calcRoute);
		function calcRoute(){
		  var start = document.getElementById('pos1').value;
		  var end = document.getElementById('pos2').value;
		  if(!start || !end) {return;}

		  start=JSON.parse(start);
		  end=JSON.parse(end);

		  var request = {
		    origin: start,
		    destination: end,
		    travelMode: 'DRIVING'
		  };
		  directionsService.route(request, function(result, status) {
		    if (status == 'OK') {
				directionsRenderer.setDirections(result);

				var leg = result.routes[0].legs[0];

				route_obj.address_start = leg.start_address;
				route_obj.address_end = leg.end_address;
				route_obj.distance = leg.distance.text;
				route_obj.distance_value = (leg.distance.value*1/1000).toFixed(2);
				route_obj.duration = leg.duration;
				console.log(route_obj);

				var routeInfo ="<div style='color:#00F'>起点:"+leg.start_address+"</div>";
				routeInfo +="<div style='color:#0F0'>终点:"+leg.end_address+"</div>";
				routeInfo +="<div>距离:"+leg.distance.text+"</div>";
				routeInfo +="<div>预计时间:"+leg.duration.text+"</div>";

				setInfo(center,routeInfo,map);

		    }else{
		    	console.log(status);
		    }
		  });
		}		

		//建立信息窗口
		function setInfo(pos,text,map){
			infoWindow.setMap(null);
			infoWindow=null;
			infoWindow = new google.maps.InfoWindow({content:text});
			infoWindow.setPosition(pos); //建立一个info
			infoWindow.open(map); //info放进地图上
			//map.setCenter(pos);  //地图中心移动到pos上
		}


		function getDetailInfo(pos){

			//查出图标的详细资料
			var service = new google.maps.places.PlacesService(map);	
			var request = {
				placeId:'xx',
				location:pos
			};

			service.getDetails(request,function(result,status){
				if(status=='OK'){
					console.log({status:status,result:result});
					var infoTxt = "<div style='font-weight:bold;color:blue;'>"+result.name+"</div><div>"+result.formatted_address+"</div>";
						infoTxt+="<div style='border-top:1px solid #ccc;'><a style='color:blue;' href='"+result.url+"'>Google for this place</a></div>";
					setInfo(pos,infoTxt,map);
					
					//document.getElementById('init_city').value="["+result.name+"]"+result.formatted_address;

					calcRoute();

				}else{
					alert('From google:['+status+']');
				}

			});
		}



		//whereIsHere();
		outTextQuery = textQuery;
		outCalcRoute = calcRoute;
		
	}

	window.onload = loadScript;

</script>